package cn.yangliu.task.service.impl;

import cn.yangliu.task.TaskFactoryBean;
import cn.yangliu.task.config.TaskProperties;
import cn.yangliu.task.dao.TaskDao;
import cn.yangliu.task.entity.Task;
import cn.yangliu.task.enums.TaskStatusEnum;
import cn.yangliu.task.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Transactional
public class TaskServiceImpl implements TaskService {

    @Resource
    private TaskDao taskDao;

    @Resource
    private TaskProperties properties;

    @Override
    public List<Task> queryAllList() {
        return taskDao.queryAllList();
    }

    @Override
    public void insert(Task task) {
        taskDao.insert(task);
        if (properties.getEnableTask()){
            TaskFactoryBean.createTask(task);
        }
    }

    @Override
    public void delete(Task task) {
        if (StringUtils.isEmpty(task.getId())) {
            throw new NullPointerException("缺少唯一主键id");
        }
        if (properties.getEnableTask()) {
            //取消任务
            TaskFactoryBean.cancleTask(task.getId());
        }
        //删除任务
        taskDao.delete(task.getId());

    }

    @Override
    public void update(Task task) {
        if (StringUtils.isEmpty(task.getClazz())) {
            throw new NullPointerException("缺少任务类clazz");
        }
        if (StringUtils.isEmpty(task.getMethod())) {
            throw new NullPointerException("缺少任务类执行方法method");
        }

        if (StringUtils.isEmpty(task.getCron())) {
            throw new NullPointerException("缺少任务时间表达式cron");
        }

        //如果页面不传任务状态
        if (task.getStatus() == null) {
            Task queryPojo = new Task();
            queryPojo.setId(task.getId());
            Task db_data = getOne(queryPojo);
            task.setStatus(db_data.getStatus());
        }

        if (properties.getEnableTask()) {
            if (TaskStatusEnum.ACTIVE.getStatus() == task.getStatus()) {
                // 重启任务
                TaskFactoryBean.restartTask(task);
            }

            if (TaskStatusEnum.STOP.getStatus() == task.getStatus()) {
                TaskFactoryBean.cancleTask(task.getId());
            }
        }
        taskDao.update(task);
    }

    @Override
    public List<Task> list(Task queryPojo) {
        return taskDao.list(queryPojo);
    }

    @Override
    public Task getOne(Task queryPojo) {
        return taskDao.getOne(queryPojo);
    }

    public void updateTaskDBInfo(Task task) {
        taskDao.update(task);
    }

    @Override
    public void resetTask() {
        taskDao.resetTask();
    }

    @Override
    public void updateExcuteCount(Task task) {
        taskDao.updateExcuteCount(task);
    }

}
